#!/bin/bash

# Smart Chat Reply 部署脚本
# 用于在阿里云服务器上部署应用

echo "🚀 开始部署 Smart Chat Reply..."

# 1. 更新系统包
echo "📦 更新系统包..."
sudo apt update

# 2. 安装 Node.js (如果未安装)
if ! command -v node &> /dev/null; then
    echo "📦 安装 Node.js..."
    curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
    sudo apt install -y nodejs
fi

# 3. 安装 Nginx (如果未安装)
if ! command -v nginx &> /dev/null; then
    echo "📦 安装 Nginx..."
    sudo apt install -y nginx
fi

# 4. 克隆或更新代码
if [ -d "/var/www/smart-chat-reply" ]; then
    echo "🔄 更新代码..."
    cd /var/www/smart-chat-reply
    git pull
else
    echo "📥 克隆代码..."
    sudo mkdir -p /var/www
    cd /var/www
    sudo git clone https://gitcode.com/gcw_ZwrkSJnT/nantong.git smart-chat-reply
    cd smart-chat-reply
fi

# 5. 安装依赖
echo "📦 安装依赖..."
npm install

# 6. 构建项目
echo "🔨 构建项目..."
npm run build

# 7. 配置 Nginx
echo "⚙️  配置 Nginx..."
sudo tee /etc/nginx/sites-available/smart-chat-reply > /dev/null <<EOF
server {
    listen 80;
    server_name your-domain.com;  # 替换为你的域名或服务器IP

    root /var/www/smart-chat-reply/dist;
    index index.html;

    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # 启用 gzip 压缩
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 缓存静态资源
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}
EOF

# 8. 启用站点
sudo ln -sf /etc/nginx/sites-available/smart-chat-reply /etc/nginx/sites-enabled/

# 9. 测试 Nginx 配置
echo "🧪 测试 Nginx 配置..."
sudo nginx -t

# 10. 重启 Nginx
echo "🔄 重启 Nginx..."
sudo systemctl restart nginx

echo "✅ 部署完成！"
echo "🌐 访问地址: http://your-domain.com"
